<?php
/**
 * Geocontexter
 * @link http://code.google.com/p/geocontexter/
 * @package Geocontexter
 */

/**
 * Admin index controller
 *
 *
 * @package Geocontexter
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @author Armand Turpel <geocontexter@gmail.com>
 * @version $Rev$ / $LastChangedDate$ / $LastChangedBy$
 */

namespace Youobserve\Controller;

use Zend\View\Model\ViewModel;
use Youobserve\Controller\AbstractController;


class LoginController extends AbstractController
{

    protected function init($controller)
    {
        $this->initView( 'youobserve/login/index.phtml', true );

        $this->view->partialData = array('active_page'    => 'login',
                                         'basePath'       => $this->getBaseUrl(),
                                         'logged_user'    => $this->view->logged_user);
    }

    public function getSessionStorage()
    {
        if (! $this->storage) {
            $this->storage = new \Geocontexter\Library\Storage();
        }

        return $this->storage;
    }

    public function indexAction()
    {
        $this->view->error = array();

        return $this->view;
    }

    /**
     * perform on the login request
     *
     */
    public function dologinAction()
    {
        $this->AuthService = $this->getServiceLocator()->get('CoreAuth');

        $username     = $this->strip_bad_code( $this->request->getPost()->username);
        $userpassword = $this->strip_bad_code( $this->request->getPost()->userpassword);

        if (empty($username) || empty($userpassword)) {
            $this->AuthService->clearIdentity();
            return $this->redirect()->toUrl($this->getBaseUrl() . '/login');
        }

        $this->AuthService->getAdapter()->setIdentity($username)
                                        ->setCredential($userpassword);

        $result = $this->AuthService->authenticate();

        if ($result->isValid()) {

            if ($this->request->getPost()->rememberme == 1 ) {

                $this->getSessionStorage()->setRememberMe(1);

                //set storage again
                $this->AuthService->setStorage($this->getSessionStorage());
            }

            $user = $this->AuthService->getAdapter()->getResultRowObject(null, array('user_password'));

            $this->AuthService->getStorage()->write($user);

            return $this->redirect()->toUrl($this->getBaseUrl());

        }

        $this->AuthService->clearIdentity();

        $this->view->error = array('Login failed');

        return $this->view;
    }

    private function strip_bad_code( $_str )
    {
        return preg_replace("/[^a-zA-Z0-9_-]/", "", $_str);
    }
}
